import 'package:sqflite/sqflite.dart';
import 'package:FiduMart/core/db/account_model.dart';
import 'package:FiduMart/core/db/sqlite.dart';

enum AddrType {
  Disable, //normal ,
  P2PKH, // bip44
  P2WPKH_P2SH, // bip49
  P2WPKH, // bip84
  P2TR, // BIP86
  P2WSH, // bip141
  P2WSH_P2SH, //bip147
}

class AccountDB extends SqliteDB {
  // 更新帐号的名称
  Future<int> updateName(String name, int id) async {
    Database db = await getDB();
    return await db.rawUpdate("update ${SqliteDB.tbAccount} set name = ? where id = ?", [name, id]);
  }

  Future<AccountModel?> getFirstReleaseAccount() async {
    Database db = await getDB();
    final List<Map<String, dynamic>> maps = await db.query(SqliteDB.tbAccount, where: "nid< 1000", orderBy: 'id asc', limit: 1);
    if (maps.length <= 0) {
      return null;
    }
    return AccountModel.fromJson(maps.first);
  }

  //根据wid取第一个账户
  Future<AccountModel?> getFirst(int wid) async {
    Database db = await getDB();
    final List<Map<String, dynamic>> maps = await db.query(SqliteDB.tbAccount, where: "wid=?", whereArgs: [wid], orderBy: 'id asc', limit: 1);
    if (maps.length <= 0) {
      return null;
    }
    return AccountModel.fromJson(maps.first);
  }

  Future<AccountModel?> getAccount(int id) async {
    Database db = await getDB();
    final List<Map<String, dynamic>> maps = await db.query(SqliteDB.tbAccount, where: "id=?", whereArgs: [id], limit: 1);
    if (maps.length <= 0) {
      return null;
    }
    return AccountModel.fromJson(maps.first);
  }

  Future<List<AccountModel>> getAccountsByWid(int wid) async {
    String? where = ' wid = ?';
    List<Object?>? whereArgs = [wid];

    Database db = await getDB();

    final List<Map<String, dynamic>> maps = await db.query(SqliteDB.tbAccount, where: where, whereArgs: whereArgs);
    if (maps.length <= 0) {
      return [];
    }
    return List.generate(maps.length, (i) {
      return AccountModel.fromJson(maps[i]);
    });
  }

  Future<List<AccountModel>> getAccountsByWNid(int walletid, int mainnid) async {
    if (walletid <= 0 && mainnid == 0) {
      return [];
    }
    String? where = '';
    List<Object?>? whereArgs = [];
    if (walletid > 0) {
      where = "wid=? and mainnid =?";
      whereArgs.add(walletid);
      whereArgs.add(mainnid);
    } else {
      where = "mainnid  =?";
      whereArgs.add(mainnid);
    }

    Database db = await getDB();

    final List<Map<String, dynamic>> maps = await db.query(SqliteDB.tbAccount, where: where, whereArgs: whereArgs);
    if (maps.length <= 0) {
      return [];
    }
    return List.generate(maps.length, (i) {
      return AccountModel.fromJson(maps[i]);
    });
  }

  Future<List<AccountModel>> getAllAccounts() async {
    Database db = await getDB();
    final List<Map<String, dynamic>> maps = await db.query(SqliteDB.tbAccount);
    if (maps.length <= 0) {
      return [];
    }
    return List.generate(maps.length, (i) {
      return AccountModel.fromJson(maps[i]);
    });
  }
}
